<template>

    <div>
        <div class="app-container">
<!--            学生信息-->
            <div class="student">
                <div class="message">
                    选课学生信息
                </div>
                <el-table :data="users" v-if="users.length">
                    <!--               选课学生信息-->
                    <el-table-column prop="userName" label="姓名"></el-table-column>
                    <el-table-column label="性别">
                        <template #default="scope">
                            {{ scope.row.sex === 0 ? '男' : scope.row.sex === 1 ? '女' : '保密' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="email" label="邮箱"></el-table-column>
                    <el-table-column prop="phonenumber" label="手机号"></el-table-column>
                </el-table>
                <p v-else class="no-courses-message">该课程还没有学生选~</p>
                <pagination
                        v-show="stutotals>0"
                        :total="stutotals"
                        v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize"
                        @pagination="fetchData"
                />
            </div>
            <div v-if="users.length">
                <!--        发布问题-->
                <div class="question">
                    <div class="message">
                        课堂问题管理
                    </div>
                    <div class="app-container">
<!--                        <el-button
                                type="primary"
                                plain
                                @click="handleAdd"
                                icon="Plus"
                                v-hasPermi="['MyTeacherCourse:MyTeacherCourse:add']"
                                style=""
                        >发布问题</el-button>-->
                                        <el-row :gutter="10" class="mb8" >
                                            <el-col :span="1.5" >
                                                <el-button
                                                        type="primary"
                                                        plain
                                                        icon="Plus"

                                                        @click="handleAdd"
                                                        v-hasPermi="['MyTeacherCourse:MyTeacherCourse:add']"
                                                        style="width: 150px;border-radius: 20px"
                                                >发布问题</el-button>
                                            </el-col>
                                        </el-row>
                        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
                            <!--                <el-table-column type="selection" width="55" align="center" />-->
                            <el-table-column label="题目" align="center" prop="title" width="180px"/>
                            <el-table-column label="内容" align="center" prop="content" />
                            <!--                <el-table-column label="答案内容" align="center" prop="answer" />-->
                            <el-table-column label="答案内容" align="center" prop="content" width="500">
                                <template #default="scope">
                                    <div class="content-div" v-html="scope.row.answer">
                                    </div></template>
                            </el-table-column>
                            <el-table-column label="截止时间" align="center" prop="deadline" width="180">
                                <template #default="scope">
                                    <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d} {h}:{i}') }}</span>
                                </template>
                            </el-table-column>
                                            <el-table-column label="答题分数" align="center" prop="answerscore" />
                            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130px">
                                <template #default="scope">
<!--                                    <el-button-->
<!--                                            type="primary"-->
<!--                                            link-->
<!--                                            @click="handleAdd"-->
<!--                                            icon="Plus"-->
<!--                                            v-hasPermi="['MyTeacherCourse:MyTeacherCourse:add']"-->
<!--                                    >发布</el-button>-->
<!--                                    <br>-->
                                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['MyTeacherCourse:MyTeacherCourse:edit']">修改问题</el-button>
                                    <br><el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['MyTeacherCourse:MyTeacherCourse:remove']">删除问题</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <pagination
                                v-show="total>0"
                                :total="total"
                                v-model:page="queryParams.pageNum"
                                v-model:limit="queryParams.pageSize"
                                @pagination="getList"
                        />
                        <!-- 添加或修改答题管理对话框 -->
                        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
                            <el-form ref="questionRef" :model="form" :rules="rules" label-width="80px">
                                <el-form-item label="题目" prop="title">
                                    <el-input v-model="form.title" placeholder="请输入提问题目"  maxlength="50" show-word-limit/>
                                </el-form-item>
                                <el-form-item label="提问内容"  prop="content">
                                    <el-input v-model="form.content" type="textarea" placeholder="请输入提问内容" :autosize="{minRows: 3, maxRows: 8 }" maxlength="200" show-word-limit/>
                                </el-form-item>
                                <el-form-item label="答案内容" prop="answer">
                                    <div class="editor-container">
                                        <editor v-model="form.answer"
                                        />
                                    </div>
                                    <!--                        <el-input v-model="form.answer" type="textarea" placeholder="请输入答案内容" :autosize="{minRows: 4, maxRows: 8 }"/>-->
                                </el-form-item>
                                <el-form-item label="截止时间" prop="deadline">

                                    <div class="block">
                                        <el-date-picker
                                                v-model="form.deadline"
                                                type="datetime"
                                                placeholder="请选择截止时间"
                                        />
                                    </div>
                                </el-form-item>
                                                    <el-form-item label="答题分数" prop="answerscore" >
                                                        <el-input v-model="form.answerscore" placeholder="请输入答题分数" />
                                                    </el-form-item>
                            </el-form>
                            <template #footer>
                                <div class="dialog-footer">
                                    <el-button type="primary" @click="submitForm">确 定</el-button>
                                    <el-button @click="cancel">取 消</el-button>
                                </div>
                            </template>
                        </el-dialog>
                    </div>
                </div>
                <!--        设置分数-->
                <div class="scores">
                    <div class="message">
                        课堂问题答题情况
                    </div>
                    <div>
<!--                        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
                            <el-table-column label="提问题目" align="center" prop="title" />
                            <el-table-column label="回答内容" align="center" prop="studentanswer" />
                            <el-table-column label="回答时间" align="center" prop="answertime" width="180">
                                <template #default="scope">
                                    <span>{{ parseTime(scope.row.answertime, '{y}-{m}-{d} {h}:{i}') }}</span>
                                </template>
                            </el-table-column>
                            &lt;!&ndash;                答题人，从users中获取&ndash;&gt;
                            <el-table-column label="答题人" align="center" prop="users.userName" />

                        </el-table>-->

                        <el-table v-loading="loading" :data="questionLists" @selection-change="handleSelectionChange">
                            <el-table-column label="提问题目" align="center">
                                <template #default="scope">
                                    <span>{{ scope.row.title || '暂无' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="回答内容" align="center">
                                <template #default="scope">
                                    <span>{{ scope.row.studentanswer || '暂无' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="回答时间" align="center" width="180">
                                <template #default="scope">
                                    <span>{{ scope.row.answertime ? parseTime(scope.row.answertime, '{y}-{m}-{d} {h}:{i}') : '暂无' }}</span>
                                </template>
                            </el-table-column>
                            <!-- 答题人，从users中获取 -->
<!--                            <el-table-column label="答题人" align="center">
                                <template #default="scope">
                                    <span>{{ scope.row.users?.userName || '暂无' }}</span>
                                </template>
                            </el-table-column>-->
                            <el-table-column label="答题人" align="center">
                                <template #default="scope">
                                    <span>{{ getUserNameById(scope.row.questionCourse.userId) || '暂无' }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <pagination
                                v-show="totals>0"
                                :total="totals"
                                v-model:page="queryParams.pageNum"
                                v-model:limit="queryParams.pageSize"
                                @pagination="getList"
                        />
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup>
    import { listQuestion, listQuestionAnser, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/question/question";
    import { onBeforeMount, ref, computed } from 'vue';
    import { useRoute } from 'vue-router';
//    selectStudentCourseList
    import { selectStudentCourseList } from '@/api/MyTeacherCourse/MyTeacherCourse';

    const { proxy } = getCurrentInstance();

    const questionList = ref([]);
    const questionLists = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const totals = ref(0);
    const stutotals = ref(0);
    const title = ref("");
    const route = useRoute();
    const courseId = ref(route.params.id);

    const users = ref([]);
    // 查找具有给定 userId 的用户
    const getUserNameById = (userId) => {
        const user = users.value.find(user => user.userId === userId);
        return user ? user.userName : undefined;
    };
    /** 获取学生信息*/
    onBeforeMount(() => {
        fetchData();
    });
    //异步获取用户信息
    const fetchData = async () => {
        try {
            const response = await selectStudentCourseList({ id: courseId.value, });
            if (response && response.rows) {
                users.value = response.rows;
                stutotals.value = response.total;
            }
        } catch (error) {
            console.error('Failed to fetch student list:', error);
        }
    };
    const data = reactive({
        form: {
            courseId: courseId.value,
            userId:localStorage.getItem('userId'),
        },
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            title: null,
            content: null,
            answer: null,
            studentanswer: null,
            questiontype: null,
            questiontime: null,
            deadline: null,
            answertime: null,
            answerscore: null,
            courseId: courseId.value,
            userId:localStorage.getItem('userId'),
        },
        rules: {
        //    title不超过50，content不超过200，answer不超过500
            title: [
                { required: true, message: "提问题目不能为空", trigger: "blur" },
                { max: 50, message: "提问题目长度不能超过50个字符", trigger: "blur" }
            ],
            content: [
                { required: true, message: "提问内容不能为空", trigger: "blur" },
                { max: 200, message: "提问内容长度不能超过200个字符", trigger: "blur" }
            ],
            answer: [
                { required: true, message: "答案内容不能为空", trigger: "blur" },
                { max: 500, message: "答案内容长度不能超过500个字符", trigger: "blur" }
            ],
            deadline: [
                { required: true, message: "截止时间不能为空", trigger: "blur" },
                {
                    validator: (rule, value, callback) => {
                        if (!value) {
                            return callback(new Error("截止时间不能为空"));
                        }

                        const deadline = new Date(value);
                        const now = new Date();

                        // 比较具体的时分秒
                        if (deadline.getTime() <= now.getTime()) {
                            callback(new Error("截止时间必须大于当前的具体时分秒"));
                        } else {
                            callback();
                        }
                    },
                    trigger: ['change', 'blur']
                }
            ],
            answerscore: [
                { required: true, message: "答题分数不能为空", trigger: "blur" },
                {
                    validator: (rule, value, callback) => {
                        if (!value) {
                            return callback(new Error("答题分数不能为空"));
                        }
                    // 使用正则表达式检查是否为0到100之间的数字，最多保留两位小数
                        const regex = /^([1-9][0-9]?|100)(\.[0-9]{1,2})?$/;
                        if (!regex.test(value)) {
                            callback(new Error("答题分数必须为0到100之间的数字，最多保留两位小数"));
                        } else {
                            callback();
                        }
                    },
                    trigger: ['change', 'blur']
                }
            ],
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询答题管理列表 和 答题列表*/
    function getList() {
        loading.value = true;
        listQuestion(queryParams.value).then(response => {
            questionList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
        listQuestionAnser(queryParams.value).then(response => {
            questionLists.value = response.rows;
            totals.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
            id: null,
            title: null,
            content: null,
            answer: null,
            studentanswer: null,
            questiontype: null,
            questiontime: null,
            deadline: null,
            answertime: null,
            answerscore: null
        };
        proxy.resetForm("questionRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加答题管理";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _id = row.id || ids.value
        getQuestion(_id).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改答题管理";
        });
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["questionRef"].validate(valid => {
            if (valid) {
                if (form.value.id != null) {
                    form.value.courseId=courseId.value;
                    updateQuestion(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    form.value.courseId=courseId.value;
                    addQuestion(form.value).then(response => {
                        proxy.$modal.msgSuccess("发布成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _ids = row.id || ids.value;
        proxy.$modal.confirm('是否确认删除答题管理编号为"' + _ids + '"的数据项？').then(function() {
            return delQuestion(_ids);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('question/question/export', {
            ...queryParams.value
        }, `question_${new Date().getTime()}.xlsx`)
    }

    getList();

    // 在DOM渲染完成后，查找所有的图片元素
    const images = document.querySelectorAll('.content-div img');
    images.forEach(img => {
        img.addEventListener('load', () => {
            adjustImageSize(img);
        });
    });

    function adjustImageSize(image) {
        // 设置图片的最大宽度和高度，使其适应容器
        image.style.maxWidth = '100%';
        image.style.maxHeight = '100%';
        // 使用object-fit属性来保持图片的宽高比
        image.style.objectFit = 'contain';
    }
</script>

<style scoped>
    .editor-container {
        width: 100%; /* 确保编辑器宽度与模态框宽度相同 */
        height: 40vh;
        /*min-height: 192px; !* 与你设定的 :min-height 相同 *!*/
        overflow-y: auto; /* 允许垂直滚动 */
        overflow-x: auto;
    }

    .content-div {
        height: 150px;
        overflow: hidden; /* 隐藏溢出的内容 */
    /*    添加滚轮*/
        overflow-y: auto;
        overflow-x: auto;
    }
    .student{
        border: #f90 2px solid;
        width: 98%;
        margin: 0 auto;
        border-radius: 40px;
        margin-bottom: 20px;
        padding-bottom: 20px;
        padding-left: 20px;
        padding-right: 20px;
    }


    .question{
        border: #6fb04c 2px solid;
        width: 98%;
        margin: 0 auto;
        border-radius: 40px;
        margin-bottom: 20px;
    }
    .scores{
        border: #369 2px solid;
        width: 98%;
        margin: 0 auto;
        border-radius: 40px;
        margin-bottom: 20px;
        height: 70vh;
    }
    .message{
        text-align: center;
        font-size: 1.8em;
        color: #726d6d;
        margin-top: 30px;
        margin-bottom: 60px;
    }

    .no-courses-message {
        text-align: center;
        font-size: 1.8em;
        color: #888;
        margin-top: 50px;
    }

</style>